package com.kodak.collin;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.StringReader;
import java.net.UnknownHostException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.json.JSONObject;
import org.json.XML;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import com.mongodb.util.*;


import com.mongodb.*;

public class Util {

	
	public static int PRETTY_PRINT_INDENT_FACTOR = 4;
	
	public static Object xml2DBObject(String filePath) throws Exception{
		JSONObject xmlJSONObj = XML.toJSONObject(XML2String(filePath));
        String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
        return JSON.parse(jsonPrettyPrintString);		
	} 
	
	public static String xml2JSONString(String filePath) throws Exception{
		JSONObject xmlJSONObj = XML.toJSONObject(XML2String(filePath));
        return xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
	}
	
	public static void String2XML(String xmlContent, String destinationFileName){
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		
		try{
			builder = factory.newDocumentBuilder();
			Document document =builder.parse(new InputSource(new StringReader(xmlContent)));
			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.transform(new DOMSource(document), new StreamResult(new File(destinationFileName)));
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static String XML2String(String fileName) throws Exception{
		BufferedReader br = new BufferedReader(new FileReader(new File(fileName)));
		String line;
		StringBuilder sb = new StringBuilder();

		while((line=br.readLine())!= null){
		    sb.append(line.trim());
		}
		
		return sb.toString();
	}
}
